<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-select v-model="listQuery.province" placeholder="省份" clearable>
            <el-option
              v-for="item in provinces"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="listQuery.industry" placeholder="行业" clearable>
            <el-option
              v-for="item in industries"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="listQuery.years"
            type="year"
            align="right"
            unlink-panels
            placeholder="选择年份"
            format="yyyy"
            value-format="yyyy"
          ></el-date-picker>
        </el-col>
        <el-col :span="3">
          <el-button
            type="primary"
            size="medium"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="medium"
            @click="handleAdd"
            >新增{{ title }}</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="wageList"
        border
        v-loading="listLoading"
        fit
        highlight-current-row
        stripe
        size="mini"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :align="column.align"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
        ></el-table-column>
        <el-table-column align="center" label="操作" width="240px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              round
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              round
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getWages"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="45%">
      <el-form
        :model="wageForm"
        :rules="wageFormRules"
        ref="wageFormRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="年份" prop="years">
          <el-date-picker
            v-model="wageForm.years"
            type="year"
            value-format="yyyy"
            placeholder="选择年份"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="省份" prop="province">
          <el-select
            v-model="wageForm.province"
            placeholder="选择省份"
            clearable
          >
            <el-option
              v-for="item in provinces"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="行业" prop="industry">
          <el-select
            v-model="wageForm.industry"
            placeholder="选择行业"
            clearable
          >
            <el-option
              v-for="item in industries"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="平均工资" prop="aver_wage">
          <el-input
            v-model="wageForm.aver_wage"
            placeholder="平均工资"
            clearable
            @input="averWageInput"
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="日平均工资" prop="day_aver_wage">
          <el-input
            v-model="wageForm.day_aver_wage"
            placeholder="日平均工资"
            clearable
          >
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave(false)">保存</el-button>
        <el-button
          type="primary"
          v-if="dialogType == 'new'"
          @click="handleSave(true)"
          >保存并增加下一个</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getIndustWage,
  addIndustWage,
  updateIndustWage,
  delIndustWage,
  getProvinceList,
  getIndustries,
} from "@/api/calculator";

import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  province: null,
  industry: null,
  years: null,
  aver_wage: 0,
  day_aver_wage: 0,
};

export default {
  name: "Wage",
  data() {
    const checkWage = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };

    return {
      wageForm: Object.assign({}, defaultForm),
      wageFormRules: {
        years: [{ required: true, message: "请选择时间", trigger: "blur" }],
        province: [{ required: true, message: "请选择省份", trigger: "blur" }],
        industry: [{ required: true, message: "请选择行业", trigger: "blur" }],
        aver_wage: [{ validator: checkWage, trigger: "blur" }],
        day_aver_wage: [{ validator: checkWage, trigger: "blur" }],
      },
      title: "行业平均工资",
      wageList: [],
      provinces: [],
      industries: [],

      dialogVisible: false,
      dialogType: "new",
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        province: "",
        industry: "",
        years: "",
      },
      tableColumns: [
        {
          key: "province_name",
          title: "省份",
          align: "left",
        },
        {
          key: "industry_name",
          title: "行业名称",
          align: "left",
        },
        {
          key: "years",
          title: "年份",
          align: "center",
        },
        {
          key: "aver_wage",
          title: "平均工资(元)",
          align: "center",
        },
        {
          key: "day_aver_wage",
          title: "日平均工资(元)",
          align: "center",
        },
      ],
    };
  },
  computed: {
    getTitle() {
      return this.dialogType == "new"
        ? `新建${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getWages();
    this.getProvinces();
    this.getIndusties();
  },
  methods: {
    // 销售单列表
    getWages() {
      this.listLoading = true;
      getIndustWage(this.listQuery)
        .then((res) => {
          this.total = res.count;
          this.wageList = res.results;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },
    getProvinces() {
      getProvinceList()
        .then((res) => {
          this.provinces = res;
        })
        .catch((error) => {
          this.$message.error("获取省份数据失败");
          console.log(error.message);
        });
    },
    getIndusties() {
      getIndustries().then((res) => {
        this.industries = res;
      });
    },
    averWageInput(value) {
      console.log(typeof +value);
      this.wageForm.day_aver_wage = parseFloat(+value / 365).toFixed(2);
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getWages();
    },
    // 增加
    handleAdd() {
      this.wageForm = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.wageFormRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      console.log(scope.row);
      this.wageForm = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs["wageFormRef"].clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delIndustWage(row.id);

          this.wageList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("删除失败!");
        });
    },
    // 保存操作
    async handleSave(flag = false) {
      console.log("HandleSave:", flag);
      this.$refs.wageFormRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          res = await updateIndustWage(this.wageForm);
          const index = this.wageList.findIndex((v) => v.id === res.id);
          this.wageList.splice(index, 1, res);
        } else {
          res = await addIndustWage(this.wageForm);
          const { id } = res;
          if (id > 0) {
            this.getWages();
          }
        }

        const {
          province_name,
          industry_name,
          years,
          aver_wage,
          day_aver_wage,
        } = res;

        if (flag) {
          // this.dialogVisible = true;
          let years = this.wageForm.years;
          let province = this.wageForm.province;
          this.wageForm = Object.assign({}, defaultForm);
          this.wageForm.years = years;
          this.wageForm.province = province;
          this.$refs.wageFormRef.clearValidate();
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>省份: ${province_name}}</div>
              <div>行业: ${industry_name}</div>
              <div>年份: ${years}</div>
              <div>平均工资: ${aver_wage}</div>
              <div>日平均工资: ${day_aver_wage}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  // .box-card{
  //   margin-top: 30px;
  // }
  .el-table {
    margin-top: 10px;
    width: 100%;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
  .el-select {
    width: 100%;
  }
  .item {
    margin-top: 8px;
  }
}
</style>